package com.wxtf.platform.main.sygl;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: neonate_detailAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.neonate_detailAction</li>
 * <li>Description: 新生儿</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 21, 2012 10:29:02 AM</li>
 * 
 * @author wangli
 * @version 1.0.0.0
 * 
 */
public class neonate_detailAction extends LogicBase implements CommonsCallProvider{
	private static final Log log = LogFactory.getLog(neonate_detailAction.class);

	public neonate_detailAction(String jsonArray){

	}
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
				return msg;
			}
			else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {
				msg = this.update(this.getLogicData());
			} else if("delete".equals(this.getMethodName())) {
				msg = this.delete(this.getLogicData());
			} else if("queryPage_tem".equals(this.getMethodName())){
				msg = this.select_tem(this.getLogicData());
				return msg;
			} else if("listAll".equals(this.getMethodName())) {//子女列表
				msg = this.listAll(this.getLogicData());
				return msg;
			}else{
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch(Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	String[] fields ={"tbfi_id","org_id","org_name","tbenm_id","tbenm_plan_status","tbenm_gravida_times","tbenm_gravida_num","tbenm_birth_time",
			"tbenm_memo","reserve1", "reserve2", "reserve3", "reserve4", "reserve5", "create_by", "create_time",
			"last_modify_by", "last_modify_time","tbend_id","tbend_name","tbend_sex","tbend_age","tbend_idcard"
			 };
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String strSql=" from (SELECT f.tbfi_id,f.org_id,f.reserve1 as org_name,m.tbenm_id,m.tbenm_plan_status,m.tbenm_gravida_times,m.tbenm_gravida_num,m.tbenm_birth_time,"+
		" m.tbenm_memo,m.reserve1,m.reserve2,m.reserve3,m.reserve4,m.reserve5,m.create_by,m.create_time,m.last_modify_by,m.last_modify_time,"+
		" d.tbend_id,d.tbend_name,d.tbend_sex,d.tbend_age,d.tbend_idcard "+
		" from tb_family_base f LEFT JOIN tbe_neonate_main m ON f.tbfi_id=m.tbfi_id LEFT JOIN tbe_neonate_detail d ON m.tbenm_id=d.tbenm_id  where tbfi_valid = '1') t";
		
		Object[] params = null;
		if("0".equals(user.getUserId())){
			sql = strSql+" where 1 = 1";
		} else {
			sql = strSql+" where t.org_id in (" + user.getCurSubOrgId() + ") ";
			params = new Object[]{ user.getCurOrgId() };
		}
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			if("init".equals(types)) {// 初始查询
				
			} else if("serch1".equals(types)) {// 条件查询
				String orgIds = jsonObject.getString("orgIds");//机构ID串

				String tbe_work_permit = jsonObject.getString("tbe_work_permit");//证件编号
				String type = jsonObject.getString("tbe_spell_code");//类别

				
				StringBuffer buff = new StringBuffer();
				if(StringUtils.isNotBlank(orgIds)){
					if(!"0".equals(orgIds)){//全部
						buff.append(" and t.org_id in ('").append(orgIds.replaceAll(",", "','")).append("')");
					}
				}

				if(StringUtils.isNotBlank(tbe_work_permit)){
					buff.append(" and t.tbend_name like '%").append(tbe_work_permit).append("%'");
				}
				
				if(StringUtils.isNotBlank(type)){
					if(!type.equals("2") && type!= "" ){
						buff.append(" and t.tbenm_plan_status like '%").append(type).append("%'");
					}
				}

				sql += buff.toString();
			}
//			else if("serch2".equals(types)) {// 高级查询
//				String where = jsonObject.getString("where");//机构ID串
//				sql += where;
//			}
		}
		// 排序
		String sortname = this.getRequest().getParameter("sortname");
		String sortorder = this.getRequest().getParameter("sortorder");
		if(sortname!=null&&sortname!=null) {
			sql += " order by " + sortname + " " + sortorder;
		}
		
		String countSql = "select count(*) " + sql;
		String querySql = "SELECT * " + sql;
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
	}	
	
	/**
	 * 临时用工查询
	 * */
    public Object select_tem(Object jsonArray) throws Exception {
      UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		Object[] params = null;
		if("0".equals(user.getUserId())){
			sql = "from tb_employee where 1 = 1 and tbe_employment_forms=(select tmgd_id from tm_general_dictionary where tmgd_name='临时工')";
		} else {
			sql = "from tb_employee where org_id = ? and tbe_employment_forms=(select tmgd_id from tm_general_dictionary where tmgd_name='临时工')";
			params = new Object[]{ user.getCurOrgId() };
		}
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			if("init".equals(types)) {// 初始查询
				
			} else{// 条件查询
				String orgIds = jsonObject.getString("orgIds");//机构ID串
				String tbe_work_permit = jsonObject.getString("tbe_work_permit");//职工号
				String tbe_name = jsonObject.getString("tbe_name");//姓名
				String tbe_spell_code = jsonObject.getString("tbe_spell_code");//拼音码
				String tbe_idcard = jsonObject.getString("tbe_idcard");//身份证
				
				StringBuffer buff = new StringBuffer();
				if(StringUtils.isNotBlank(orgIds)){
					if(!"0".equals(orgIds)){//全部
						buff.append(" and org_id in ('").append(orgIds.replaceAll(",", "','")).append("')");
					}
				}
				if(StringUtils.isNotBlank(tbe_work_permit)){
					buff.append(" and tbe_work_permit like '%").append(tbe_work_permit).append("%'");
				}
				if(StringUtils.isNotBlank(tbe_name)){
					buff.append(" and tbe_name like '%").append(tbe_name).append("%'");
				}
				if(StringUtils.isNotBlank(tbe_spell_code)){
					buff.append(" and tbe_spell_code like '%").append(tbe_spell_code.toUpperCase()).append("%'");
				}
				if(StringUtils.isNotBlank(tbe_idcard)){
					buff.append(" and tbe_idcard like '%").append(tbe_idcard).append("%'");
				}
				sql += buff.toString();
			}
		}
		// 排序
		String sortname = this.getRequest().getParameter("sortname");
		String sortorder = this.getRequest().getParameter("sortorder");
		if(sortname!=null&&sortname!=null) {
			sql += " order by " + sortname + " " + sortorder;
		}
		
		String countSql = "select count(*) " + sql;
		String querySql = "select tbe_id,org_id,tbe_idcard,tbe_work_permit,tbe_employment_forms,tbe_name,tbe_former_name,tbe_spell_code,tbe_sex,tbe_age,tbe_birthday,tbe_nation,tbe_native_palce,tbe_birthplace,tbe_join_time,tbe_seniority,tbe_family_phone,tbe_mobile,tbe_address,tbe_marital_status,tbe_marital_condition,tbe_married_time,tbe_marriage_certificate,tbe_political_status,tbe_qualification,tbe_graduate_college,tbe_major,tbe_work_area,tbe_position,tbe_is_again_birth,tbe_is_barrenness,tbe_is_late_marriage,tbe_is_late_birth,tbe_status,tbe_ba_status,tbe_birth_control_measures,tbe_es_time,tbe_is_es,tbe_es_reason,tbe_children_status,tbe_order,tbe_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time " + sql;
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
    }
	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		
		StringBuffer buff = new StringBuffer();
		StringBuffer buff2 = new StringBuffer();
		buff.append("insert into tbe_neonate_main(tbenm_id");
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
			buff.append(",").append(fields[j]);
		}
		buff.append(") values(");
		obj[0] = AccessDataBaseUtil.getPKUUID();
		
		String curTime = FormatUtil.getCurentDateTime();
		obj[48] = user.getUserId();
		obj[49] = curTime;
		obj[50] = user.getUserId();
		obj[51] = curTime;
		
		for(int i=0; i<obj.length; i++){
			if(i == 9 || i == 15){
				buff2.append(obj[i]).append(",");
			} else {
				buff2.append("'").append(obj[i]).append("',");
			}
		}
		buff2.deleteCharAt(buff2.length() - 1);
		String sql1 = buff.append(buff2.toString()).append(")").toString();
		sql = "insert into tbe_neonate_detail(tbfi_id,org_id,tbe_id,tbfi_children_num,tbfi_children_mnum,tbfi_children_fnum,tbfi_valid,create_by,create_time,last_modify_by,last_modify_time) values('" + AccessDataBaseUtil.getPKUUID() + "','" + obj[1] + "','" + obj[0] + "',0,0,0,1,'" + obj[48] + "','" + obj[49] + "','" + obj[50] + "','" + obj[51] + "')";
		String[] sqls = { sql1, sql };
		
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "\"保存成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String curTime = FormatUtil.getCurentDateTime();
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		StringBuffer buff = new StringBuffer();
		buff.append("update tbe_neonate_main set ");
		Object[] obj = new Object[fields.length];
		for(int j = 1; j < fields.length; j++) {
			obj[j - 1] = jsonObject.getString(fields[j]);
			buff.append(fields[j]).append(" = ?,");
		}
		buff.deleteCharAt(buff.length() - 1).append(" where tbefbr_id = ?");
		obj[21] = user.getUserId();
		obj[22] = curTime;
		obj[23] = jsonObject.getString("tbefbr_id");
		
		AccessDataBaseUtil.executeSQLUpdate(buff.toString(), obj);
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		sql = "delete from tbe_only_child_record where tbeocr_id = ?";
		
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	
	/** 
	 * 描述：listAll 查看所有的人员
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 28, 2012  1:31:49 PM
	 * @author chun_chang
	 */
	public Object listAll(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tbe_name = jsonObject.getString("tbe_name");
		String tbe_idcard = jsonObject.getString("tbe_idcard");
		
		sql = " from tb_employee where tbe_id not in(select r.tbe_spouse_id from tb_family_base r where r.tbe_spouse_id is not null)";
		if(StringUtils.isNotBlank(tbe_name)){
			sql += " and tbe_name like '%" + tbe_name + "%'";
		}
		if(StringUtils.isNotBlank(tbe_idcard)){
			sql += " and tbe_idcard like '%" + tbe_idcard + "%'";
		}
		
		String countSql = "select count(*)" + sql;
		String querySql = "select tbe_id,tbe_idcard,tbe_name,tbe_sex,tbe_age,tbe_birthday,org_id,reserve1,tbe_position" + sql;
		String[] fields = {
			"tbe_id","tbe_idcard","tbe_name","tbe_sex","tbe_age","tbe_birthday","org_id","reserve1","tbe_position"
		};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	
	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}
}